﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demos.DesignPatterns._01_Singleton
{

    /// <summary>
    /// 单例模式测试
    /// </summary>
    public class SingletonClass
    { 
        //volatile 保证 instance 在所有线程中同步 确保线程安全
        private static volatile  SingletonClass _SingletonObject = null;
        
        private static object obj = new object();

        /// <summary>
        /// 防止被外部实例化修改
        /// </summary>
        private SingletonClass()
        {
            this.Id = 1;
            this.Name = "张三";
        }
        /// <summary>
        /// 实例化对象
        /// </summary>
        /// <returns></returns>
        public static SingletonClass Instance()
        {
            if(_SingletonObject == null)
            {
                //增加锁防止多线程创建多次
                lock (obj)
                {
                    if(_SingletonObject == null)
                    {
                        lock (obj)
                        {
                            _SingletonObject = new SingletonClass();
                        }
                    }
                }
            }
            return _SingletonObject;
        }   

        /// <summary>
        /// Id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// Name
        /// </summary>
        public string Name { get; set; }

    }
}
